# backend/routers/book_router.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from backend.crud import book_crud
from backend.database import get_db
from backend.dependencies import get_current_active_user
from backend.models import User, LibraryMember
from backend.schemas import Book, BookCreate
from backend.services import isbn_service

router = APIRouter()


@router.post("/books/isbn", response_model=Book)
async def add_book_by_isbn(
        isbn: str,
        library_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    # 验证用户是否属于该书阁
    if not db.query(LibraryMember).filter(
            LibraryMember.library_id == library_id,
            LibraryMember.user_id == current_user.id
    ).first():
        raise HTTPException(status_code=403, detail="不属于该书阁")

    return await isbn_service.add_book_by_isbn(db, isbn, library_id, current_user.id)


@router.post("/books/manual", response_model=Book)
def add_book_manual(
        book: BookCreate,
        library_id: int,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    # 验证用户是否属于该书阁
    if not db.query(LibraryMember).filter(
            LibraryMember.library_id == library_id,
            LibraryMember.user_id == current_user.id
    ).first():
        raise HTTPException(status_code=403, detail="不属于该书阁")

    return book_crud.create_book(
        db=db,
        isbn=book.isbn,
        title=book.title,
        author=book.author,
        cover_url=book.cover_url or "",
        library_id=library_id,
        added_by=current_user.id
    )


@router.get("/books/search")
def search_books(
        library_id: int,
        query: str,
        db: Session = Depends(get_db),
        current_user: User = Depends(get_current_active_user)
):
    return book_crud.search_books(db, library_id, query)
